package gfx.layers;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifSubIFDDirectory;

public class Layer{
	protected BufferedImage image;
	private BufferedImage thumb;
	private String name;
	private LayerManager layerManager;
	private Metadata metadata;
	private boolean isSelected = true;
	private int thumbSize = 40;
	
	protected Layer(String name, LayerManager layerManager){
		this.layerManager = layerManager;
		this.name = name;
	}
	
	public Layer(File file, String name, LayerManager layerManager){
		this(name, layerManager);
		try {
			image = ImageIO.read(file);
			metadata = ImageMetadataReader.readMetadata(file);
    }
		catch (IOException e) {
	    e.printStackTrace();
    }
		catch (ImageProcessingException e) {
	    e.printStackTrace();
    }
	}
	
	public Layer(BufferedImage image, String name, LayerManager layerManager){
		this(name, layerManager);
		this.image = image;
	}
	
	public BufferedImage getImage(){
		return image;
	}
	
	public String getName(){
		return name;
	}
	
	public LayerManager getLayerManager(){
		return layerManager;
	}
	
	public int getThumbSize(){
		return thumbSize;
	}

	public BufferedImage getThumbnail(){
		if(thumb == null){
			float ratio = (float)image.getWidth() / (float)image.getHeight();
			
			thumb = new BufferedImage(thumbSize, thumbSize, BufferedImage.TYPE_INT_ARGB);
			if(ratio > 0){
				int width = (int)((float)thumbSize * ratio);
				thumb.getGraphics().drawImage(
						image, 
						(thumbSize - width) / 2,
						0,
						width,
						thumbSize,
						null);
			}
			else{
				int height = (int)((float)thumbSize / ratio);
				thumb.getGraphics().drawImage(
						image, 
						0,
						(thumbSize - height) / 2,
						thumbSize,
						height,
						null);
			}
		}
		return thumb;
	}
	
	public String getExifShutterSpeed(){
		if(metadata != null && metadata.containsDirectory(ExifSubIFDDirectory.class)){
			ExifSubIFDDirectory exifSubIfdDirectory = metadata.getDirectory(ExifSubIFDDirectory.class);
			return exifSubIfdDirectory.getString(ExifSubIFDDirectory.TAG_EXPOSURE_TIME);
		}
		return null;
	}
	
	public void setSelected(boolean isSelected){
		this.isSelected = isSelected;
	}
	
	public boolean isSelected(){
		return isSelected;
	}
}
